package com.nursing.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nursing.Dao.CarePlanDao;
import com.nursing.Dao.CareTaskDao;
import com.nursing.bean.CarePlan;
import com.nursing.bean.CareTask;
import com.nursing.model.dto.CareTaskDto;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TaskService {
    private final CareTaskDao careTaskDao;
    private final CarePlanDao carePlanDao;

    public TaskService(CareTaskDao careTaskDao, CarePlanDao carePlanDao) {
        this.careTaskDao = careTaskDao;
        this.carePlanDao = carePlanDao;
    }

    public void addTask(CareTask careTask) {
        // 查询是否被分配过了
        careTaskDao.getByPlanId(careTask.getPlanId()).forEach(task -> {
            if (task.getNurseId().equals(careTask.getNurseId()) && task.getStatus().equals("待执行")) {
                throw new RuntimeException("该任务已被分配");
            }
        });

        careTask.setStatus("待执行");
        careTask.setTaskDetails("");
        careTask.setExecutedAt(LocalDateTime.now());
        // 创建任务
        careTaskDao.insert(careTask);
        // 更新护理计划状态
        CarePlan carePlan = carePlanDao.getById(careTask.getPlanId());
        carePlan.setStatus(1);
        carePlanDao.update(carePlan);
    }

    public void deleteTask(Integer id) {
        careTaskDao.delete(id);
    }

    public PageInfo<CareTaskDto> list(int page, int size) {
        PageHelper.startPage(page, size);
        List<CareTaskDto> tasks = careTaskDao.getAll();
        return new PageInfo<>(tasks);
    }

    public void finishTask(CareTask careTask) {
        careTask.setStatus("已完成");
        careTask.setExecutedAt(LocalDateTime.now());
        careTaskDao.update(careTask);
    }
}
